package com.heima.juc.unlock;

import lombok.extern.slf4j.Slf4j;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.LongAdder;
import java.util.function.Consumer;
import java.util.function.Supplier;

/**
 * @author : leimingchao
 * @date Date : 2022年02月12日 20:34
 */
@Slf4j(topic = "c.Test7")
public class Test7 {

    public static void main(String[] args) {
        // demo(() -> new AtomicLong(0), adder -> adder.getAndIncrement());
        demo(() -> new AtomicLong(0), AtomicLong::getAndIncrement);

        demo(() -> new LongAdder(), LongAdder::increment);
    }

    private static <T> void demo(Supplier<T> adderSupplier, Consumer<T> action) {
        T adder = adderSupplier.get();

        List<Thread> ts = new ArrayList<>();

        //4个线程，每人累加50万
        for (int i = 0; i < 4; i++) {
            ts.add(new Thread(() -> {
                for (int j = 0; j < 500000; j++) {
                    action.accept(adder);
                }
            }));

        }
        LocalDateTime start = LocalDateTime.now();

        ts.forEach(Thread::start);

        ts.forEach(t -> {
            try {
                t.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        LocalDateTime end = LocalDateTime.now();

        log.debug(adder + " cost: {} 毫秒", Duration.between(start, end).toMillis());
    }
}
